package com.wjerp.tplus.server.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wjerp.tplus.server.api.controller.base.BaseController;
import com.wjerp.tplus.server.common.constant.VerInvoiceSearchResult;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.exception.ServiceException;
import com.wjerp.tplus.server.common.model.WxApiResponseData;
import com.wxapi.WxApiCall.WxApiCall;
import com.wxapi.model.RequestModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 京东万象API操作类
 * @author lishuailei
 */
@Component
public class WxApiUtils {

    /** The logger. */
    public static Logger logger = LoggerFactory.getLogger(WxApiUtils.class);

    @Value("${wxApi.gwUrl}")
    private String gwUrl;
    @Value("${wxApi.appKey}")
    private String appKey;

    /**
     * 发票验真
     * 参考地址：https://wx.jdcloud.com/market/datas/30/12706
     * @param invoiceCode 发票代码
     * @param invoiceNumber 发票号码
     * @param invoiceDate 开票日期：YYYY-MM-DD
     * @param amount 合计金额（不含税），必须精确到两位小数（专票、货运专票、机动车专票必填）
     * @param checkCode 校验码后6位（普票、电子普票、卷式普票必填
     * @return 查询结果
     */
    public  WxApiResponseData verInvoice(String invoiceCode,String invoiceNumber,
                              String invoiceDate,String amount,String checkCode) throws BusinessException, ServiceException {
        RequestModel model = new RequestModel();
        model.setGwUrl(gwUrl);
        model.setAppkey(appKey);
        Map queryMap = new HashMap(4);
        queryMap.put("invoiceCode",invoiceCode);
        queryMap.put("invoiceNumber",invoiceNumber);
        queryMap.put("billingDate",invoiceDate);
        queryMap.put("totalAmount",amount);
        queryMap.put("checkCode",checkCode);
        model.setQueryParams(queryMap);
        WxApiCall call = new WxApiCall();
        call.setModel(model);
        String result = call.request();
        logger.info("verInvoice-request{0},verInvoice-result{1}",queryMap,result);
        WxApiResponseData wxApiResponseData = JSON.parseObject(result, WxApiResponseData.class);
        VerInvoiceSearchResult verInvoiceSearchResult = VerInvoiceSearchResult.resolve(wxApiResponseData.getCode());
        if(!verInvoiceSearchResult.equals(VerInvoiceSearchResult.SUCCESS)){
            logger.error("verInvoice--发票校验失败，失败信息{0}",result);
            throw new BusinessException("发票校验失败");
        }
        //获取返回的对象信息
        JSONObject responseResult = wxApiResponseData.getResult();
        //获取返回消息体的状态，status = 2 代表查询成功，其他的都是查询失败
        JSONObject messageResult =  responseResult.getJSONObject("message");
        Integer status = messageResult.getInteger("status");
        if(!status.equals(2)){
            throw new ServiceException(messageResult.getString("value"));
        }

        //TODO：待实现


        return wxApiResponseData;
    }
}
